#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc,char *argV[]){
	char recv_buf[2048]="";
	int sockfd=0;
	int connfd=0;
	int err_log=0;
	struct sockaddr_in my_addr;
	unsigned short port=8000;
	printf("TCP Server Started at port %d\n",port);
	sockfd=socket(AF_INET,SOCK_STREAM,0);
	bzero(&my_addr,sizeof(my_addr));
	my_addr.sin_family=AF_INET;
	my_addr.sin_port  =htons(port);
	my_addr.sin_addr.s_addr=htonl(INADDR_ANY);
	
	printf("Binding server to port %d\n",port);

	err_log=bind(sockfd,(struct sockaddr*)&my_addr,sizeof(my_addr));
	if(err_log !=0)
	{
		perror("binding");
		close(sockfd);
		exit(-1);
	}
	err_log=listen(sockfd,10);
	if(err_log!=0){
		perror("listen");
		close(sockfd);
		exit(-1);
	}
	printf("Waiting client...\n");
	
	while(1)
	{
		size_t recv_len=0;
		struct sockaddr_in client_addr;
		char cli_ip[INET_ADDRSTRLEN]="";
		socklen_t cliaddr_len =sizeof(client_addr);

		connfd = accept(sockfd,(struct sockaddr*)&client_addr,&cliaddr_len);
		if(connfd<0)
		{
			perror("accept");
			continue;
		}
		inet_ntop(AF_INET,&client_addr.sin_addr,cli_ip,INET_ADDRSTRLEN);
		printf("client ip =%s\n",cli_ip);
		while((recv_len =recv(connfd,recv_buf,sizeof(recv_buf),0))>0)
		{
			send(connfd,recv_buf,recv_len,0);
		}
		close(connfd);
		printf("client close!\n");
	}

	close(sockfd);
	return 0;

}
